package me.chenjp.tracker.service;

import me.chenjp.tracker.core.funtion.ExampleFunction;
import me.chenjp.tracker.core.mapper.CommonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;

/**
 * @author: Chenjp
 * @description: 这个人很懒, 没有留下任何注释
 * @create: 2019-03-26 10:37
 */
public abstract class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    protected CommonMapper<T> mapper;

    protected Class<?> clazz;

    public BaseServiceImpl(){ init(); }

    private void init(){
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType){
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            this.clazz = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
    }

    @Override
    public Class<?> getParameterizedClass(){ return this.clazz; }

    @Override
    public Optional<T> selectByKey(Object key) { return Optional.ofNullable(mapper.selectByPrimaryKey(key)); }

    @Override
    public int save(T entity) { return mapper.insertSelective(entity); }

    @Override
    public int deleteByPrimaryKey(Object key) { return mapper.deleteByPrimaryKey(key); }

    @Override
    public int updateAll(T entity) { return mapper.updateByPrimaryKey(entity); }

    @Override
    public int delete(T entity) { return mapper.delete(entity); }

    @Override
    public int deleteByExample(T entity) { return mapper.deleteByExample(entity); }

    @Override
    public int updateNotNull(T entity) { return mapper.updateByPrimaryKeySelective(entity); }

    @Override
    public List<T> selectByExample(Object example) { return mapper.selectByExample(example); }

    @Override
    public List<T> selectByExample(ExampleFunction function){
        Example example = new Example(clazz);
        Example.Criteria criteria = example.createCriteria();
        return mapper.selectByExample(function.get(example, criteria));
    }

    @Override
    public List<T> select(T var1) { return mapper.select(var1); }

    @Override
    public Optional<T> selectOne(T entity) { return Optional.ofNullable(mapper.selectOne(entity)); }

    @Override
    public List<T> selectAll() { return mapper.selectAll(); }

    @Override
    public int insertSelective(T entity) { return mapper.insertSelective(entity); }

    @Override
    public int selectCount(T entity) { return mapper.selectCount(entity); }

    @Override
    public int insertList(List<T> recordList) { return mapper.insertList(recordList); }
}
